package sk.stuba.fiit.ltasys.web.mvc.model.dao.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import sk.stuba.fiit.ltasys.web.mvc.model.dao.UserDao;
import sk.stuba.fiit.ltasys.web.mvc.model.entity.UserEntity;

/**
 * Person DAO implementation.
 * 
 * @author Marek Hruska
 */

@Repository("userDaoImpl")
@Transactional(readOnly = true)
public class UserDaoImpl implements UserDao {

	@Autowired
	protected SessionFactory sessionFactory = null;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}
	
	protected HibernateTemplate template = null;

	@SuppressWarnings("unchecked")
	public Collection<UserEntity> findUsers() throws DataAccessException {
		return template.find("from User");
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void save(UserEntity userEntity) {
		template.saveOrUpdate(userEntity);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(UserEntity userEntity) {
		template.delete(userEntity);
	}

	public UserEntity findUserById(String id) throws DataAccessException{
		return template.get(UserEntity.class, id);
	}

	@Transactional(readOnly = false)
	public void deleteUserByName(String name) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<UserEntity> result = session.createCriteria(UserEntity.class).add(Restrictions.eq(UserEntity.USERNAME, name)).list();
		UserEntity user = result.get(0);
		if(user!= null){
			session.delete(user);
			transaction.commit();
		}else{
			transaction.rollback();
		}
		session.close();
	}

	public UserEntity findUserByUserName(String username) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<UserEntity> result = session.createCriteria(UserEntity.class).add(Restrictions.eq(UserEntity.USERNAME, username)).list();
		UserEntity user= null;
		if(result.size()>=1){
			user = result.get(0);
		}
		transaction.rollback();
		session.close();
		
		if(user!= null){
			return user;
		}else{
			return new UserEntity();
		}
	}

}
